PHP中有很多方法解析XML. 本文单表使用DOM解析XML.
要进行解析的XML:
13999910** [email protected] [网络异常]服务器: {ID}网络异常
进行解析的PHP代码:
/** * 解析XML, 创建Site, 返回Site列表. * @param $xmlPath * @return unknown_type */ public static function loadSitesFormXML($xmlPath) { $xml = new DOMDocument(); // 创建DOM $xml->load($xmlPath);//'sites.xml'); // 加载XML $sitesXml = $xml->getElementsByTagName("site"); // 根据Name获得Elements列表. $arraySites = array(); foreach($sitesXml as $site) { // 遍历每一个Element. $site = self::createSite($site); // 转入createSite()方法进一步解析DOMElement, 创建并返回Site对象. $arraySites[$site->id] = $site; } // logMesg("
XML解析完毕, 共获得Stie对象: ".count($arraySites), false); return $arraySites; } /** * 解析给定的DOMElement, 创建并返回Site对象. * @param $site * @return unknown_type */ public static function createSite(DOMElement $site) { $id = $site->getAttribute("id"); // 获得Attribute ID $url = $site->getAttribute("url"); // 获得Attribute URL $expectedReturnString = $site->getAttribute("expectedReturnString"); $timeOut = $site->getAttribute("timeOut"); $maxRetries = $site->getAttribute("maxRetries"); $minErrorReportInterval = $site->getAttribute("minErrorReportInterval"); $notifySmsToElement = $site->getElementsByTagName("notifySmsTo"); // 获得Element: 手机短信发送对象 $notifySmsTo = $notifySmsToElement->item(0)->nodeValue; $notifySmsBodyElement = $site->getElementsByTagName("notifySmsBody"); $notifySmsBody = $notifySmsBodyElement->item(0)->nodeValue; $notifyEmailToElement = $site->getElementsByTagName("notifyEmailTo"); $notifyEmailTo = $notifyEmailToElement->item(0)->nodeValue; $notifyEmailSubjectElement = $site->getElementsByTagName("notifyEmailSubject"); $notifyEmailSubject = $notifyEmailSubjectElement->item(0)->nodeValue; $notifyEmailBodyElement = $site->getElementsByTagName("notifyEmailBody"); $notifyEmailBody = $notifyEmailBodyElement->item(0)->nodeValue; return $site = new Site($id, $url, $expectedReturnString, $timeOut, $maxRetries, $minErrorReportInterval, $notifySmsTo, $notifySmsBody, $notifyEmailTo, $notifyEmailSubject, $notifyEmailBody); }
参考:
0. PHP手册DOMDocument: http://php.net/manual/en/class.domdocument.php
1. IBM DW :Reading and writing the XML DOM with PHP
2. 解读PHP DOMDocument在解析XML文件中的作用
PHP: Sending Html/plain Email by mb_send_mail 发送HTML/Plain格式的邮件 <->
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.